package com.sf.osms.dep.processor.persistor;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sf.osms.dep.biz.ICommonServiceBiz;
import com.sf.osms.dep.domain.Agent;
import com.sf.osms.dep.domain.Router;
import com.sf.osms.dep.domain.RouterProblemRecord;
import com.sf.osms.dep.processor.exception.ExceptionConstants;
import com.sf.osms.dep.processor.model.EventModel;
import com.sf.osms.dep.processor.util.CollectionUtil;
import com.sf.osms.dep.processor.util.ExceptionUtils;
import com.sf.osms.dep.processor.util.FileUtil;
import com.sf.osms.dep.processor.util.JdbcUtils;
import com.sf.osms.dep.processor.util.PropertiesUtil;
import com.sf.osms.dep.processor.util.RouterConstants;
import com.sf.osms.dep.processor.util.SwitchUtils;
import com.sf.osms.dep.processor.util.WebserviceUtil;
import com.sf.osms.dep.webservice.email.EmailSender;
import com.sf.osms.dep.webservice.fvp.BarRecordBaseDto;
import com.sf.osms.dep.webservice.fvp.Exception_Exception;

public class CommonEventPersistor implements EventPersistor<String[],Router>{
	
	private static Logger logger = LoggerFactory.getLogger(CommonEventPersistor.class);
	private ICommonServiceBiz commonService;
	
	public CommonEventPersistor(){
		
	}
	public CommonEventPersistor(ICommonServiceBiz commonService) {
		this.commonService = commonService;
	}
	
	@Override
	public void persist(EventModel<String[], Router> eventModel,
			Agent agentInfo) throws Exception{
		
		List<Router> routers = eventModel.getCorrectRouter();
		//进行路由的拆分
		
		//进行正确路由的处理
		handleCorrectRouterList(routers,eventModel,agentInfo);
		
		
		//进行批量需要handover的路由信息插入
		if(!CollectionUtil.isEmpty(eventModel.getNeedHandleRouter())){
			commonService.insertRouterTmp(eventModel.getNeedHandleRouter());
		}
		
		List<RouterProblemRecord> routerProblemRecords = eventModel.getErrorEventRecord();
		if(!CollectionUtil.isEmpty(routerProblemRecords)){
			//进行错误记录入库操作
			try {
				commonService.insertRouterProblemBatch(routerProblemRecords);
				//进行错误记录的邮件发送
				String lineContent = agentInfo.getName() + ":</br>hello,your router file have some errors." + "The error content of line router : </br>";
			
				for (RouterProblemRecord routerProblemRecord : routerProblemRecords) {
					
					lineContent = lineContent + routerProblemRecord.getErrorDesc();
					String[] errorCodes = routerProblemRecord.getErrorCode().split(",");
					for (String errorCode : errorCodes) {
						if(null != ExceptionConstants.errorEnDesc.get(errorCode)){
							lineContent = lineContent + "</br> (the reason of error is " + ExceptionConstants.errorEnDesc.get(errorCode) +").</br>";
						}
					}
						
				}
				//进行邮件发送
				EmailSender es = new EmailSender();
				es.setContent(lineContent);
				es.setSubject("dep file error(" + agentInfo.getBackPath() + "/" + eventModel.getFile().getName() + ")");
				String defReceive = PropertiesUtil.getProperty("dep.mail.to");
				if(StringUtils.isBlank(defReceive)){
					defReceive = RouterConstants.DEP_MAIL_TO;
				}
				if(StringUtils.isNotBlank(agentInfo.getAgentEmailSet())){
					defReceive = defReceive + "," + agentInfo.getAgentEmailSet();
				}
				es.setDefReceive(defReceive);
				if(SwitchUtils.getSwithBySystemName(SwitchUtils.EMAIL_SWITCH_NAME)){
					WebserviceUtil.invokeEmail(es);
				}
			
			} catch (Exception e1) {
				logger.error("******代理：" + agentInfo.getName() + "调用insertRouterProblemBatch失败！******" + ExceptionUtils.getExceptionStackString(e1));
			}
			//错误条数的处理
			//handleErrorFile(eventModel,agentInfo);
		}
		
		//调用接口
		//inovkeFVPInterface(routerSet,agentInfo);
		
	}
	
	
	/**
	 * 进行正确路由信息的处理
	 * @param routers
	 * @param eventModel
	 * @param agentInfo
	 * @throws Exception
	 */
	private void handleCorrectRouterList(List<Router> routers,EventModel<String[],Router> eventModel,Agent agentInfo) throws Exception{
		if(!CollectionUtil.isEmpty(routers)){
		   //进行批量插入操作
			try {
				if(!CollectionUtil.isEmpty(routers)){
					JdbcUtils.saveBatch(routers);
					//commonService.insertRouterBatch(routerSet);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("******代理：" + agentInfo.getName() + 
						",路由文件为" + eventModel.getFile().getAbsolutePath()+"中批量插入路由信息异常******");
				throw e;
			}
				
		}
	}
	
	//调用fvp接口
	private void inovkeFVPInterface(Set<Router> routers, Agent agentInfo) throws Exception{
		if(CollectionUtil.isEmpty(routers)){
			return;
		}
		
		List<BarRecordBaseDto> barRecordBaseDtos = new ArrayList<BarRecordBaseDto>();
		for (Router router : routers) {
			try {
				BarRecordBaseDto brb = commonService.mapBean(router, BarRecordBaseDto.class);
				barRecordBaseDtos.add(brb);
				logger.info("******代理：" + agentInfo.getName() + 
						",路由文件为" + router.getFileName() + "转化为,BarRecordBaseDto记录："+brb.toString()+""
						+"******");
			} catch (Exception e) {
				logger.error("******代理：" + agentInfo.getName() + 
						",路由文件为" + router.getFileName() + ",router记录："+router.toString()+"中出现映射到fvp对象出现异常"
						+".******");
			}
		}
		
		boolean result = false;
		try {
			result = WebserviceUtil.invokeFvp(barRecordBaseDtos);
		} catch (Exception_Exception e) {
			logger.error("******代理：" + agentInfo.getName() + 
					",路由文件为" + routers.iterator().next().getFileName() + ",调用fvp接口异常！"
					+".******");
			e.printStackTrace();
			RouterProblemRecord routerProblemRecord = new RouterProblemRecord();
			routerProblemRecord.setAgentName(agentInfo.getName());
			routerProblemRecord.setFileName(routers.iterator().next().getFileName());
			routerProblemRecord.setCreateTime(new Date());
			routerProblemRecord.setErrorDesc("调用fvp接口异常");
			try {
				commonService.insertRouterProblem(routerProblemRecord);
			} catch (Exception er) {
				er.printStackTrace();
				logger.error("******代理：" + agentInfo.getName() + 
						",路由文件为" + routers.iterator().next().getFileName() + ",存放RouterProblem信息异常！"
						+".******");
			}
		}
		
		if(!result){
			RouterProblemRecord routerProblemRecord = new RouterProblemRecord();
			routerProblemRecord.setAgentName(agentInfo.getName());
			routerProblemRecord.setFileName(routers.iterator().next().getFileName());
			routerProblemRecord.setCreateTime(new Date());
			routerProblemRecord.setErrorDesc("调用fvp接口异常");
			try {
				commonService.insertRouterProblem(routerProblemRecord);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("******代理：" + agentInfo.getName() + 
						",路由文件为" + routers.iterator().next().getFileName() + ",存放RouterProblem信息异常！"
						+".******");
			}
		}else{
			logger.info("******代理：" + agentInfo.getName() + "成功调用fvp接口！******");
		}
		
	}
	private void handleErrorFile(EventModel<String[], Router> eventModel,
			Agent agentInfo) {
		
		File errorRecordFile = eventModel.getFile();
	    List<RouterProblemRecord> errorEventRecordList = eventModel.getErrorEventRecord();
	    if(CollectionUtil.isEmpty(errorEventRecordList)){
	    	return;
	    }
	    String emailTitle = "Track file contain error record";
		StringBuilder sb = new StringBuilder(errorEventRecordList.size() * 300);
		sb.append("  Our systerm  have downloaded the track file named "+FileUtil.getTreeFileName(errorRecordFile.getName())+" and the file is owned by "+agentInfo.getName()+",but the file contains some errors.  Details：<br/>");
		/*for (RouterProblemRecord trackProblemRecord : errorEventRecordList) {
			sb.append(" the error reason:<br/>");
			sb.append(trackProblemRecord.getErrorDesc()).append("<br/> the error original line's content: <br/>")
					.append(trackProblemRecord.getErrorLine()).append("<br/>-----------------------------------<br/>");
		}*/
		//进行错误记录入库操作
		try {
			commonService.insertRouterProblemBatch(errorEventRecordList);
		} catch (Exception e1) {
			logger.error("******代理：" + agentInfo.getName() + "调用insertRouterProblemBatch失败！******");
		}
		/*try {
			
			String content = "";
			if (errorRecordFile.length() / RouterConstants.MB > 1) {// 文件大小，大于等于2MB时，只发送文件路径
				content += "file path:" + agentInfo.getBackPath() + "/" + errorRecordFile.getName()+"</br>";
				SendMailUtil.sendMail(emailTitle, content + sb.toString(),null);
			} else {
				SendMailUtil.sendMailWithAttachment(emailTitle, sb.toString(),null, new String[] {errorRecordFile.getAbsolutePath()});
			}
		} catch (Exception e) {
			logger.warn(agentInfo.getName() + errorRecordFile.getName() + " send email fail:" + e.getMessage());
		}*/
	}
	
	public ICommonServiceBiz getCommonService() {
		return commonService;
	}

	public void setCommonService(ICommonServiceBiz commonService) {
		this.commonService = commonService;
	}
	
	public static void main(String[] args) {
		System.out.println(101/100);
	}
	
	 private <T> List<List<T>> split(List<T> resList,int count){
		    
		    if(resList==null ||count<1)
		      return  null ;
		    List<List<T>> ret=new ArrayList<List<T>>();
		    int size=resList.size();
		    if(size<=count){ //数据量不足count指定的大小
		      ret.add(resList);
		    }else{
		      int pre=size/count;
		      int last=size%count;
		      //前面pre个集合，每个大小都是count个元素
		      for(int i=0;i<pre;i++){
		        List<T> itemList=new ArrayList<T>();
		        for(int j=0;j<count;j++){
		          itemList.add(resList.get(i*count+j));
		        }
		        ret.add(itemList);
		      }
		      //last的进行处理
		      if(last>0){
		        List<T> itemList=new ArrayList<T>();
		        for(int i=0;i<last;i++){
		          itemList.add(resList.get(pre*count+i));
		        }
		        ret.add(itemList);
		      }
		    }
		    return ret;
		    
		  }
}
